<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑分类' : '新建分类'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入分类名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="路径" prop="slug">
            <el-input
              v-model="form.slug"
              placeholder="请输入分类路径（如：technology）"
              maxlength="50"
              show-word-limit
            >
              <template #prepend>/category/</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入分类描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio value="active">启用</el-radio>
          <el-radio value="inactive">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <!-- 关系管理区域 -->
    <div v-if="isEdit" class="relation-section">
      <el-divider>关系管理</el-divider>
      
      <el-row :gutter="20">
        <!-- 关联页面 -->
        <el-col :span="12">
          <div class="relation-group">
            <h4>关联页面</h4>
            <div class="relation-content">
              <!-- 当前关联的页面 -->
              <div v-if="currentRelatedPages.length > 0" class="current-relations">
                <h5>已关联页面:</h5>
                <div class="relation-list">
                  <el-tag
                    v-for="page in currentRelatedPages"
                    :key="page.id"
                    closable
                    @close="removePageRelation(page.id)"
                    class="relation-tag"
                  >
                    {{ page.title }}
                  </el-tag>
                </div>
              </div>
              
              <!-- 添加页面关联 -->
              <div class="add-relation">
                <h5>添加页面关联:</h5>
                <el-select
                  v-model="selectedPageId"
                  placeholder="选择要关联的页面"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="page in availablePages"
                    :key="page.id"
                    :label="page.title"
                    :value="page.id"
                  />
                </el-select>
                <el-button
                  type="primary"
                  size="small"
                  @click="addPageRelation"
                  :disabled="!selectedPageId"
                  style="margin-top: 10px; width: 100%"
                >
                  添加关联
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 关联项目 -->
        <el-col :span="12">
          <div class="relation-group">
            <h4>关联项目</h4>
            <div class="relation-content">
              <!-- 当前关联的项目 -->
              <div v-if="currentRelatedItems.length > 0" class="current-relations">
                <h5>已关联项目:</h5>
                <div class="relation-list">
                  <el-tag
                    v-for="item in currentRelatedItems"
                    :key="item.id"
                    closable
                    @close="removeItemRelation(item.id)"
                    class="relation-tag"
                    type="warning"
                  >
                    {{ item.title }}
                  </el-tag>
                </div>
              </div>
              
              <!-- 添加项目关联 -->
              <div class="add-relation">
                <h5>添加项目关联:</h5>
                <el-select
                  v-model="selectedItemId"
                  placeholder="选择要关联的项目"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="item in availableItems"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  />
                </el-select>
                <el-button
                  type="primary"
                  size="small"
                  @click="addItemRelation"
                  :disabled="!selectedItemId"
                  style="margin-top: 10px; width: 100%"
                >
                  添加关联
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  pages: {
    type: Array,
    default: () => []
  },
  items: {
    type: Array,
    default: () => []
  },
  tempPageRelations: {
    type: Array,
    default: () => []
  },
  tempItemRelations: {
    type: Array,
    default: () => []
  }
})

// Events
const emit = defineEmits([
  'update:visible', 
  'save', 
  'cancel',
  'add-page',
  'remove-page',
  'add-item',
  'remove-item'
])

// 响应式数据
const formRef = ref()
const saving = ref(false)
const selectedPageId = ref(null)
const selectedItemId = ref(null)
const form = ref({
  name: '',
  slug: '',
  description: '',
  status: 'active'
})

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 当前关联的页面
const currentRelatedPages = computed(() => {
  if (!props.isEdit || !props.formData.id) return []
  return props.pages.filter(page => 
    page.categories && page.categories.some(cat => cat.id === props.formData.id)
  )
})

// 当前关联的项目
const currentRelatedItems = computed(() => {
  if (!props.isEdit || !props.formData.id) return []
  return props.items.filter(item => 
    item.categories && item.categories.some(cat => cat.id === props.formData.id)
  )
})

// 可用的页面（未关联的）
const availablePages = computed(() => {
  if (!props.isEdit || !props.formData.id) return props.pages
  return props.pages.filter(page => 
    !page.categories || !page.categories.some(cat => cat.id === props.formData.id)
  )
})

// 可用的项目（未关联的）
const availableItems = computed(() => {
  if (!props.isEdit || !props.formData.id) return props.items
  return props.items.filter(item => 
    !item.categories || !item.categories.some(cat => cat.id === props.formData.id)
  )
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度应在 1 到 50 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入分类路径', trigger: 'blur' },
    { 
      pattern: /^[a-z0-9-]+$/, 
      message: '路径只能包含小写字母、数字和连字符', 
      trigger: 'blur' 
    },
    { min: 1, max: 50, message: '路径长度应在 1 到 50 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择分类状态', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    slug: '',
    description: '',
    status: 'active'
  }
  selectedPageId.value = null
  selectedItemId.value = null
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData && Object.keys(newData).length > 0) {
      form.value = {
        name: newData.name || '',
        slug: newData.slug || '',
        description: newData.description || '',
        status: newData.status || 'active',
        ...newData
      }
    } else {
      resetForm()
    }
  },
  { immediate: true, deep: true }
)

// 监听名称变化，自动生成路径
watch(
  () => form.value.name,
  (newName) => {
    if (newName && !props.isEdit && !form.value.slug) {
      // 自动生成 slug
      const slug = newName
        .toLowerCase()
        .replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '')
      form.value.slug = slug
    }
  }
)



// 添加页面关联
const addPageRelation = () => {
  if (selectedPageId.value) {
    emit('add-page', props.formData.id, selectedPageId.value)
    selectedPageId.value = null
  }
}

// 移除页面关联
const removePageRelation = (pageId) => {
  emit('remove-page', props.formData.id, pageId)
}

// 添加项目关联
const addItemRelation = () => {
  if (selectedItemId.value) {
    emit('add-item', props.formData.id, selectedItemId.value)
    selectedItemId.value = null
  }
}

// 移除项目关联
const removeItemRelation = (itemId) => {
  emit('remove-item', props.formData.id, itemId)
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    const formData = { ...form.value }
    
    // 如果是编辑模式，保留原有的 ID
    if (props.isEdit && props.formData.id) {
      formData.id = props.formData.id
    }
    
    emit('save', formData)
    
    ElMessage.success(props.isEdit ? '分类更新成功' : '分类创建成功')
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  } finally {
    saving.value = false
  }
}

// 处理关闭
const handleClose = () => {
  emit('cancel')
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.relation-section {
  margin-top: 20px;
}

.relation-group {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafbfc;
}

.relation-group h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.relation-group h5 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 13px;
  font-weight: 500;
}

.current-relations {
  margin-bottom: 20px;
}

.relation-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.relation-tag {
  margin: 0;
}

.add-relation {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  color: #909399;
  border-color: #dcdfe6;
}
</style>